import { useState } from "react";
import { Contact } from "./interface";
import ContactList from "./ContactList";
import EditContact from "./EditContact";

const initialContacts: Contact[] = [
  { id: 0, name: "Taylor", email: "taylor@mail.com" },
  { id: 1, name: "Alice", email: "alice@mail.com" },
  { id: 2, name: "Bob", email: "bob@mail.com" }
];
function ContactManager() {
  const [contacts, setContacts] = useState(initialContacts);
  const [selectedId, setSelectedId] = useState(0);

  const selectedContact = contacts.find(contact => contact.id === selectedId);

  const handleSave = (updateData: Contact) => {
    const nextContacts = contacts.map(contact => {
      if (contact.id === updateData.id) {
        return updateData;
      } else {
        return contact;
      }
    });

    setContacts(nextContacts);
  };

  return (
    <div>
      <ContactList contacts={contacts} selectedId={selectedId} onSelect={id => setSelectedId(id)} />
      <hr />
      <EditContact key={selectedContact?.id} savedContact={selectedContact!} onSave={handleSave} />
    </div>
  );
}

export default ContactManager;
